<?php
/**
 * 字典库
 * User: lxl
 * Date: 2020/07/22
 */

namespace App\Model\Core\Sys;


use App\Model\CoreModel;
use App\Service\ParamsService;

class SysDictModel extends CoreModel
{
    protected string $table = 'sys_dict';

    /**
     * 根据ID获取单条字典信息
     * @param int $id
     * @param bool $is_cache
     * @return array
     */
    public function getOne(int $id, bool $is_cache = true): array
    {
        if ($id <= 0) return [];
        return $this->cache($id, function () use ($id) {
            return obj_to_array($this->getConnectionTable()->where('id', $id)->first());
        }, $is_cache);
    }

    /**
     * 根据标题获取单条字典信息
     * @param string $dict_sub_val
     * @return array
     */
    public function checkIdByDictSubVal(string $dict_sub_val, int $id = 0): array
    {
        $query = $this->getConnectionTable()->where('dict_sub_val', $dict_sub_val);
        if (!empty($id)) $query->where('id', '!=', $id);
        return obj_to_array($query->first());
    }

    /**
     * 获取全部字典信息
     * @param $dict_item
     * @param int $status
     * @param string $order
     * @return array
     */
    public function getAllByItem($dict_item, int $status = 0, string $order = 'sort_order'): array
    {
        if (empty($dict_item)) return [];
        $query_obj = $this->getConnectionTable()->where('dict_item', $dict_item);
        $query_obj->where('status', $status);
        $query_obj->orderByDesc($order);
        $query_obj->orderByDesc('id');
        return obj_to_array($query_obj->get());
    }

    /**
     * 添加字典信息
     * @param array $data
     * @return int|bool
     */
    public function addOne(array $data): int|bool
    {
        if (empty($data)) return false;
        return $this->getConnectionTable()->insertGetId($data);
    }

    /**
     * 更新字典信息
     * @param int $id
     * @param array $data
     * @return bool
     */
    public function updateOne(int $id, array $data): bool
    {
        if ($id <= 0 || empty($data)) return false;
        if (empty($old_info = self::getOne($id))) return false;
        if ($res = $this->getConnectionTable()->where('id', $id)->update($data)) {
            self::clearCache($old_info);
        }
        return $res;
    }

    /**
     * 清空缓存
     * @param array $info
     * @return $this
     */
    public function clearCache(array $info): self
    {
        $this->cleanCache($info['id']);
        return $this;
    }

}
